/**
 * time: 2025-09-16
 * author: XJ
 * description: 产品基本信息页面
 */

import { CheckCircleOutlined, CloseCircleOutlined, InboxOutlined, SyncOutlined, UploadOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { useLocation, useModel, useNavigate } from '@umijs/max';
import { Button, Cascader, Divider, Form, Input, message, Modal, Row, Select, Space, Steps, TreeSelect, Upload } from 'antd';
import Dragger from 'antd/es/upload/Dragger';
import { Col } from 'antd/lib';
import area from '@/components/staticFile/region_options.json';
import TextArea from 'antd/es/input/TextArea';
import condition from '@/components/staticFile/treeSelect.json';
import ReactQuill from 'react-quill';
import { useEffect, useState } from 'react';
import { auditProduct, govermentAuditProduct, updateProduct } from '@/services/apis/serviceProviderRegister';
import { uploadFile } from '@/services/apis/companyRegister';
const COMMON_FIELD_STYLE = { width: '100%', height: 40, borderRadius: 4 };
const FORM_LAYOUT = {
    labelCol: { span: 6 }, // 调整标签宽度，避免长标签换行
    wrapperCol: { span: 18 },
    layout: 'horizontal' as const,
    
    size: 'middle' as const, // 统一表单控件尺寸
};
const ProductAllInfosPage: React.FC<{ searchCallFun: any }> = (props) => {
    const {
        modalProps,
        setModalProps,
    } = useModel("ProductManager.modal")
    const location = useLocation();
    const navigate = useNavigate();
    const [showList, setShowList] = useState<any[]>([]);
    const [otherList, setOtherList] = useState<any[]>([]);
    const { initialState, setInitialState } = useModel('@@initialState');
    const [form] = Form.useForm()
    const handleAutoUpload = async (file: any, formPath: any) => {

        try {
            const response = await uploadFile(file)
            if (response.code == "0") {
                //message.success("上传成功")
                form.setFieldValue(formPath, [response.data])
                if (formPath == "productShow") {
                    setShowList(prev => ([...prev, { name: response.data.filename, uid: Math.random().toString() }]))
                } else {
                    setOtherList(prev => ([...prev, { name: response.data.filename, uid: Math.random().toString() }]))
                }
                // handleSuccess(data, file);

            }
        } catch (error) {
            // handleError(error, file);
        }
    };
    const handleSubmit = () => {
        form.validateFields().then(values => {
            updateProduct({ ...values, id: modalProps.record.id }).then(res => {
                const { code } = res;
                if (code == "0") {
                    // //message.success("更新产品信息成功")
                    navigate("/api_status_page", {
                        state: {
                            title: "产品信息更新",
                            message: "产品信息更新成功",
                            callbackUrl: location.pathname
                        }
                    });
                    setModalProps(prev => ({ ...prev, visible: false }))
                }
            })
        })
    };
    useEffect(() => {
        form.setFieldsValue(modalProps.record)
        setShowList(modalProps.record.productShow)
        setOtherList(modalProps.record.otherInfo)
    }, [modalProps.record])
    const onCancel = () => {
        setModalProps(prev => ({ ...prev, visible: false }))
    }
    const onFinishFailed = (values: any) => { };

    async function handleReviewSubmit(arg0: string) {
        await form.validateFields()
        govermentAuditProduct({
            auditStatus: arg0,
            auditRemark: form.getFieldValue("auditRemark"),
            id: modalProps.record.companyId,
            auditUserId: initialState?.currentUser?.data.id,
            auditId: modalProps.record.auditId,
            userType: initialState?.currentUser?.data.userType,
            // auditDepartment:initialState?.currentUser?.data.departmentName
        }).then(res => {
            const { code } = res;
            if (code == "0") {
                setModalProps(prev => ({ ...prev, visible: false }))

                navigate("/api_status_page", {
                    state: {
                        title: "产品审核",
                        message: "产品审核成功",
                        callbackUrl: location.pathname
                    }
                });
                // //message.success("操作成功")
                props.searchCallFun();
            }
        })

    }

    return (
        <Modal
            title={modalProps.title}
            open={modalProps.visible}
            onCancel={onCancel}
            footer={modalProps.title == "审核产品" ? null : [
                <Button key="back" onClick={onCancel}>
                    取消
                </Button>,
                <Button key="submit" type="primary"
                    onClick={handleSubmit}
                >
                    提交
                </Button>,
            ]}
            width={900}
            destroyOnClose
            maskClosable={false}
        >
            <Form
                {...FORM_LAYOUT}
                form={form}

            // name="basic"
            // labelCol={{ span: 8 }}
            // wrapperCol={{ span: 16 }}
            // style={{ maxWidth: '100%', paddingLeft: '20%', paddingRight: '20%' }}
            // initialValues={{ remember: true }}
            // onFinish={onFinish}
            // onFinishFailed={onFinishFailed}
            // autoComplete="off"
            // layout="vertical"
            >
                <div style={{ padding: 20, backgroundColor: '#f8f9fa', boxSizing: 'border-box' }}>
                    <div
                        style={{
                            backgroundColor: '#fff',
                            padding: 20,
                            borderRadius: 8,
                            boxShadow: '0 1px 3px rgba(0,0,0,0.05)',
                        }}
                    >
                        <div
                            style={{
                                fontSize: 16,
                                fontWeight: 500,
                                color: '#1f2937',
                                marginBottom: 12,
                            }}
                        >
                            基本信息
                        </div>
                        <Form.Item
                            label="产品名称"
                            name="productName"
                            rules={[{ required: true, message: '请输入产品名称' }]}
                        >
                            <Input disabled={modalProps.title == "审核产品"}
                                className={modalProps.title == "审核产品" ? 'custom-readonly-input' : ''} placeholder="请输入产品名称" />
                        </Form.Item>
                        {/* <Form.Item
          label="所属城市"
          name="city"
          rules={[{ required: true, message: '请选择所在城市' }]}
        >
          <TreeSelect
            allowClear
            placeholder="请选择注册城市"
            treeData={area}
            // style={COMMON_FIELD_STYLE}
          />
        </Form.Item> */}
                        <Form.Item
                            label="购买方式"
                            name="purchaseWay"
                            rules={[{ required: true, message: '请选择购买方式' }]}
                        >
                            <Select
                                allowClear
                                disabled={modalProps.title == "审核产品"}
                                placeholder="请选择购买方式"
                                className={modalProps.title == "审核产品" ? 'custom-readonly-select' : ''}
                                options={[
                                    { value: 'once', label: '一次性购买' },
                                    { value: 'need', label: '按需购买' },
                                    { value: 'subscribe', label: '订阅' },
                                    { value: 'month', label: '包月计费' },
                                    { value: 'year', label: '包年计费' },
                                    { value: 'needPay', label: '按需计费' },
                                    { value: 'other', label: '其他' },
                                ]}
                            />
                        </Form.Item>
                        <Form.Item
                            label="部署架构"
                            name="deploymentArchitecture"
                            rules={[{ required: true, message: '请选择部署架构' }]}
                        >
                            <Select
                                allowClear
                                disabled={modalProps.title == "审核产品"}
                                placeholder="请选择部署架构"
                                className={modalProps.title == "审核产品" ? 'custom-readonly-select' : ''}
                                options={[
                                    { value: 'CS', label: 'C/S' },
                                    { value: 'BS', label: 'B/S' },
                                    { value: 'PC', label: 'PC单机' },
                                    { value: 'danji', label: '单机部署' },
                                    { value: 'duoji', label: '多机/集群部署' },
                                    { value: 'wfy', label: '微服务架构部署' },
                                    { value: 'rqh', label: '容器化部署' },
                                    { value: 'hh', label: '混合部署' },
                                    { value: 'by', label: '边缘计算部署' },
                                    { value: 'yys', label: '云原生部署' },
                                    { value: 'qt', label: '其他' },
                                ]}
                            />
                        </Form.Item>
                        <Form.Item
                            label="报价区间"
                        // name="price"
                        // rules={[{ required: true, message: '请输入报价区间' }]}
                        >
                            <Space>
                                <Form.Item
                                    noStyle

                                    name="priceHigh"
                                    rules={[{ required: true, message: '请输入报价区间最小值' }]}
                                >
                                    <Input
                                        className={modalProps.title == "审核产品" ? 'custom-readonly-input' : ''}
                                        disabled={modalProps.title == "审核产品"} placeholder="报价区间最小值" />
                                </Form.Item>
                                ——
                                <Form.Item
                                    noStyle

                                    name="priceLow"
                                    rules={[{ required: true, message: '请输入报价区间最大值' }]}
                                >
                                    <Input
                                        className={modalProps.title == "审核产品" ? 'custom-readonly-input' : ''}
                                        disabled={modalProps.title == "审核产品"} placeholder="报价区间最大值" />
                                </Form.Item>
                            </Space>
                        </Form.Item>

                        <Form.Item
                            label="产品展示主视觉"
                            name="productShow"
                            rules={[{ required: true, message: '请上传产品主视觉' }]}
                        >
                            <Upload disabled={modalProps.title == "审核产品"}
                                accept='.jpg,.jpeg,.bmp,.png'
                                fileList={showList && showList.map(item => ({ ...item, name: item.filename }))}
                                beforeUpload={(file) => {
                                    // 选择文件后立即触发自动上传
                                    handleAutoUpload(file, "productShow");
                                    return false; // 阻止组件默认自动上传行为，使用自定义逻辑
                                }}
                                listType="text"
                                maxCount={1}
                            >
                                <Button disabled={modalProps.title == "审核产品"} icon={<UploadOutlined />}>点击上传(图片尺寸为300*180，不得超过1M； 支持JPG, JPEG, BMP, PNG格式;)</Button>
                            </Upload>
                        </Form.Item>
                        <Form.Item
                            label="其他资料"
                            name="otherInfo"
                            rules={[{ required: true, message: '请上传其他资料' }]}
                        >
                            <Upload disabled={modalProps.title == "审核产品"}
                                fileList={otherList && otherList.map(item => ({ ...item, name: item.filename }))}
                                beforeUpload={(file) => {
                                    // 选择文件后立即触发自动上传
                                    handleAutoUpload(file, "otherInfo");
                                    return false; // 阻止组件默认自动上传行为，使用自定义逻辑
                                }}
                                listType="text"
                                maxCount={1}
                            >
                                <Button disabled={modalProps.title == "审核产品"} icon={<UploadOutlined />}>上传附件，不大于5M</Button>
                            </Upload>
                        </Form.Item>
                        <div
                            style={{
                                fontSize: 16,
                                fontWeight: 500,
                                color: '#1f2937',
                                marginBottom: 12,
                            }}
                        >
                            产品描述
                        </div>
                        <Form.Item
                            name="productEvaluation"
                            label="产品简介"
                            rules={[{ required: true, message: '请输入产品简介' }]}
                            style={{ marginBottom: 20 }}
                        >
                            <TextArea
                                readOnly={modalProps.title == "审核产品"}
                                className={modalProps.title == "审核产品" ? 'custom-readonly-textarea' : ''}
                                maxLength={500}
                                showCount
                                style={{
                                    minHeight: 100,
                                    resize: 'vertical',
                                    ...COMMON_FIELD_STYLE,
                                }}
                            />
                        </Form.Item>
                        <Form.Item
                            name="productDetail"
                            label="产品详情"
                            rules={[{ required: true, message: '请输入产品详情' }]}
                            style={{ marginBottom: 20 }}
                        >
                            <TextArea
                                maxLength={500}
                                readOnly={modalProps.title == "审核产品"}
                                showCount
                                style={{
                                    minHeight: 100,
                                    resize: 'vertical',
                                    ...COMMON_FIELD_STYLE,
                                }}
                            />
                        </Form.Item>
                        <div
                            style={{
                                fontSize: 16,
                                fontWeight: 500,
                                color: '#1f2937',
                                marginBottom: 12,
                            }}
                        >
                            使用场景
                        </div>

                        <Form.Item
                            name="industry"
                            label="所属行业"
                            rules={[{ required: true, message: '请选择所属行业' }]}
                        >
                            <Select className={modalProps.title == "审核产品" ? 'custom-readonly-select' : ''} disabled={modalProps.title == "审核产品"} placeholder="请选择所属行业" style={{ width: '100%' }}>
                                <Select.Option value="制造业">制造业</Select.Option>
                                <Select.Option value="服务业">服务业</Select.Option>
                                <Select.Option value="金融业">金融业</Select.Option>
                                <Select.Option value="医疗健康">医疗健康</Select.Option>
                                <Select.Option value="教育行业">教育行业</Select.Option>
                            </Select>
                        </Form.Item>

                        <Form.Item
                            name="subIndustry"
                            label="细分行业"
                            rules={[{ required: true, message: '请选择细分行业' }]}
                        >
                            <Select className={modalProps.title == "审核产品" ? 'custom-readonly-select' : ''} disabled={modalProps.title == "审核产品"} mode="multiple" placeholder="请选择细分行业" style={{ width: '100%' }}>
                                <Select.Option value="汽车制造">汽车制造</Select.Option>
                                <Select.Option value="电子信息">电子信息</Select.Option>
                                <Select.Option value="物流运输">物流运输</Select.Option>
                                <Select.Option value="餐饮服务">餐饮服务</Select.Option>
                                <Select.Option value="软件开发">软件开发</Select.Option>
                            </Select>
                        </Form.Item>

                        <Form.List name="digitalContentList">
                            {(fields, { add, remove }) => (
                                <>
                                    {fields.map(({ key, name, ...restField }) => (
                                        <div
                                            key={key}
                                            style={{
                                                marginBottom: 24,
                                                borderBottom: '1px solid #e8e8e8',
                                                paddingBottom: 16,
                                            }}
                                        >
                                            <Form.Item
                                                {...restField}
                                                label="场景"
                                                name={[name, 'sceneName']}
                                                rules={[{ required: true, message: '请选择场景' }]}
                                                style={{ marginBottom: 20 }}
                                            >
                                                <Cascader
                                                    disabled={modalProps.title == "审核产品"}
                                                    allowClear
                                                    className={modalProps.title == "审核产品" ? 'custom-readonly-select' : ''}
                                                    placeholder="请选择场景"
                                                    style={COMMON_FIELD_STYLE}
                                                    options={condition}
                                                    // treeDefaultExpandAll
                                                    fieldNames={{ label: 'title' }}
                                                    showSearch
                                                // onChange={(value) => {
                                                //   if (value) {
                                                //     const fullPath = fullPathMap[value].join(' / ');
                                                //     form.setFieldValue(['scenes', name, 'scene'], fullPath);
                                                //   }
                                                // }}
                                                />
                                            </Form.Item>

                                            <Form.Item
                                                {...restField}
                                                label="场景描述"
                                                name={[name, 'sceneDesc']}
                                                rules={[{ required: true, message: '请输入场景描述' }]}
                                                style={{ marginBottom: 20 }}
                                            >
                                                <ReactQuill
                                                    theme="snow"
                                                    // value={value}
                                                    // onChange={setValue}
                                                    readOnly={modalProps.title == "审核产品"}
                                                    placeholder="请输入场景描述"
                                                    style={{
                                                        minHeight: 180,
                                                        background: '#fff',
                                                        borderRadius: 8,
                                                    }}
                                                    modules={{
                                                        toolbar: [
                                                            ['bold', 'italic', 'underline', 'strike'],
                                                            [{ list: 'ordered' }, { list: 'bullet' }],
                                                            ['link', 'image'],
                                                            [{ align: [] }],
                                                            ['clean'],
                                                        ],
                                                    }}
                                                    className="custom-quill-editor"
                                                />
                                            </Form.Item>
                                        </div>
                                    ))}
                                    {/* 
                                    <Form.Item wrapperCol={{ offset: 5, span: 19 }} style={{ marginTop: 40 }}>
                                        <Button type="dashed" onClick={() => add()} block>
                                            + 新增场景
                                        </Button>
                                    </Form.Item> */}
                                </>
                            )}
                        </Form.List>
                        {
                            modalProps.title == "审核产品" && (
                                <>
                                    {/* 审核意见（必填） */}
                                    <Divider>审核意见</Divider>
                                    <Form.Item
                                        name="auditRemark"
                                        label={
                                            <span>
                                                审核意见 <span style={{ color: 'red' }}>*</span>
                                            </span>
                                        }
                                        rules={[{ required: true, message: '请填写审核意见' }]}
                                    >
                                        <TextArea
                                            rows={4}
                                            placeholder="请输入审核意见（如：产品信息完整，同意通过；或：缺少技术规格，需退回补充）"
                                        />
                                    </Form.Item>

                                    {/* 审核操作按钮：通过/不通过/退回 */}
                                    <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '16px', marginTop: '16px' }}>
                                        <Button onClick={() => setModalProps(prev => ({ ...prev, visible: false }))}>
                                            取消
                                        </Button>
                                        <Button
                                            danger
                                            icon={<CloseCircleOutlined />}
                                            onClick={() => handleReviewSubmit('rejected')}
                                        >
                                            不通过
                                        </Button>
                                        <Button
                                            icon={<SyncOutlined />}
                                            onClick={() => handleReviewSubmit('returned')}
                                        >
                                            退回
                                        </Button>
                                        <Button
                                            type="primary"
                                            icon={<CheckCircleOutlined />}
                                            onClick={() => handleReviewSubmit('approved')}
                                        >
                                            通过
                                        </Button>
                                    </div>
                                </>
                            )
                        }

                    </div>
                </div>
            </Form>
        </Modal>
    )
}

export default ProductAllInfosPage;